
//
//  JBWComposeViewController.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/7/8.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit
import AFNetworking

class JBWComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = randomColor()
        setupUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //设置视图
    private func setupUI(){
        setupNav()
        //添加控件
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(bottomView)
        //添加约束
        textView.snp.makeConstraints { (make) in
//            make.edges.equalTo(view)
            make.top.left.bottom.right.equalTo(view)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: JBWSCREENW - 20, height: JBWSCREENW - 20))
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(35)
        }
        
        //闭包实例化
//        bottmView.closure = {(type)->() in
        bottomView.closure = {[weak self](type)->() in
            //闭包回调
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .add:
                print("+")
            case .emotion:
                print("表情")
                self?.switchKeyboard()
          
            }
        }
        
        //监听加号按钮点击
        pictureView.closure = {[weak self] in
            self?.selectImage()
        }
        
        //监听系统通知监听按键
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //监听表情键盘20个按钮点击
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClickNoti), name: JBWEMOTICONBUTTONCLICKNOTI, object: nil)
        //监听表情键盘中删除按钮通知
        NotificationCenter.default.addObserver(self, selector: #selector(deleteBUttonClickNoti), name: JBWDELETEBUTTONCLICKNOTI, object: nil)
    }

    //设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView:senfButton )
        //默认不能点击
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        navigationItem.titleView = titleView
    }
    
    //懒加载控件
    private lazy var senfButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(sendClick), for: UIControlEvents.touchUpInside)
        button.setBackgroundImage(UIImage( named:"common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: UIControlState.disabled)
        button.setTitle("发送", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: JBWNormalFontSize)
        button.frame.size = CGSize(width: 50, height: 35)
        return button
        
    }()
    
    //titleView
    private lazy var titleView: UILabel = {
        //获取名字
        let name = JBWOAuthViewModel.share.userAccountModel?.screen_name ?? ""

        //最终要显示的文字
        let str = "发微博\n\(name)"
        //范围
        let range = (str as NSString).range(of: name)
        //通过字符串获取富文本
        let attr = NSMutableAttributedString(string: str)
        //设置富文本属性
        attr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName: JBWThemeColor], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.attributedText = attr
        lab.textAlignment = .center
        lab.sizeToFit()
        return lab
        
    }()
    
    //自定义textView
    fileprivate lazy var textView: JBWComposeTextView = {
        let view = JBWComposeTextView()
        view.placeholder = "请输入你要发送的微博"
        view.font = UIFont.systemFont(ofSize: 16)
        view.delegate = self
        //上下滚动
        view.alwaysBounceVertical = true
        return view
        
    }()
    //底部视图
    fileprivate lazy var bottomView: JBWComposeBottomView = JBWComposeBottomView()
    //自定义配图
    fileprivate lazy var pictureView: JBWComposePictureView = JBWComposePictureView()
    //自定义表情键盘
    fileprivate lazy var keyboardView: JBWEmoticonKeyboardView = JBWEmoticonKeyboardView()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

//底部视图按钮点击事件监听
extension JBWComposeViewController {
        fileprivate func selectImage(){
            //打开相册
            let pickerVC = UIImagePickerController()
            //设置代理
            pickerVC.delegate = self
            //是否可以编辑
//            pickerVC.allowsEditing = true
            //是否可以打开相机及相册
//            UIImagePickerController.isFlashAvailable(for: UIImagePickerControllerSourceType)
            //前后摄像头是否可以
//            UIImagePickerController.isFlashAvailable(for: UIImagePickerControllerCameraDevice.front)
            
            self.present(pickerVC, animated: true , completion: nil)
            
        }
    
    //切换键盘
    func switchKeyboard(){
        //self.textView.inputView == nil  表示系统键盘 反之就是表情键盘
//        if self.textView.inputView == nil {
//            self.textView.inputView = keyboardView
//        } else {
//            self.textView.inputView = nil
//        }
        
        self.textView.inputView = (self.textView.inputView == nil ? keyboardView : nil)
        //赋值
        self.bottomView.isEmoticon = (self.textView.inputView != nil)
        //刷新inputview
        self.textView.reloadInputViews()
        //开启第一响应者
        self.textView.becomeFirstResponder()
    }
    }


// UIImagePickerControllerDelegate
extension JBWComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //通过key获取Image
        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
            return
        }
        
        //赋值
        pictureView.addImage(image: image.dealImageScale(maxWidth: 400))
        picker.dismiss(animated: true, completion: nil)
    }
}
extension JBWComposeViewController: UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //取消第一响应者
        self.textView.resignFirstResponder()
    }
}
//监听事件
extension JBWComposeViewController{
    @objc fileprivate func cancelClick(){
        dismiss(animated: true, completion: nil)
        print("取消")
    }
    @objc fileprivate func sendClick(){
    print("发送")
        
        print(textView.attributedText)
        //记录最终的字符串
        var allText = ""
        //遍历
        textView.attributedText.enumerateAttributes(in: NSRange(location: 0, length: textView.attributedText.length), options: []) {(info, range, _) in
        //图片表情
            if let att = info["NSAttachment"] as? JBWTextAttachment {
            allText += textView.attributedText.attributedSubstring(from: range).string
            } else {
                //字符串
                allText += textView.attributedText.attributedSubstring(from: range).string
            }
        }
        print(allText)
        //发送图文微博还是文字微博
        pictureView.imageList.count > 0 ? upload(status: allText) : update(status: allText)
    }

    
    //发布文字微博
    func update(status: String){
        //url地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        //请求参数
        let params = [
            "access_token": JBWOAuthViewModel.share.accessToken,
            "status": status]
        //简单的post请求
        JBWNetworkTools.share.request(type: JBWNetworkToolsType.post, urlString: urlString, parameters: params, success: { (response) in
            
        }) { (error) in
            
        }
        
        
    }

    //发布图片和文字微博
    func upload(status: String){
        //url地址
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        //请求参数
        let params = [
            "access_token": JBWOAuthViewModel.share.accessToken,
            "status": status]
        
        //上传一张图片
        let image = pictureView.imageList.first!
        //把图片转二进制
        let d = UIImagePNGRepresentation(image)!
        
        //发送请求
        JBWNetworkTools.share.post(urlString, parameters: params, constructingBodyWith: { (formdata) in
            //单张图片
            formdata.appendPart(withFileData: d, name: "pic", fileName: "testtest", mimeType: "application/octet-stream")
            
//            //如果是多张图片
//            for image in self.pictureView.imageList{
//                //把图片转二进制
//                let d = UIImagePNGRepresentation(image)!
//                formdata.appendPart(withFileData: d, name: "pic", fileName: "testtest", mimeType: "application/octet-stream")
//            }
        }, progress: nil, success: { (_, response) in
            
        }) { (_, error) in
            
        }
    }
}

//监听通知方法
extension JBWComposeViewController {
    //监听键盘frame变化
    @objc fileprivate func keyboardWillChangeFrame(noti: Notification){
        
        //判断是否为nil
        guard let userInfo = noti.userInfo else {
            return
            }
        //获取rect
        let rect = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        //获取动画时长
        let duration = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        //更新底部视图的底部约束
        self.bottomView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(rect.origin.y - JBWSCREENH)
        }
        
        //设置动画
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    //监听20个annual点击
    @objc fileprivate func emoticonButtonClickNoti(noti: NSNotification){
        //判断是否为nil 切是否可以转成emoticonModel
        guard let emoticonModel = noti.object as? JBWEmoticonModel else { return
        }
        
        //判断是emoji 还是图片表情
        if emoticonModel.isEmoji {
            //emoji
            let code = ((emoticonModel.code ?? "") as NSString).emoji() ?? ""
            //设置给textView
            textView.insertText(code)
            
        } else {
            //图片表情
            //在每次进入当前判断中后 保存当前 textView.attributedText
            let allAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            //通过路径获取image
            let allPath = emoticonModel.allPath ?? ""
            //读取bundle文件中的图片
            let image = UIImage(named: allPath, in: JBWEmoticonTools.share.emoticonBundle, compatibleWith: nil)
            //创建一个文本附件
            let att = JBWTextAttachment()
            
            //赋值
            att.emoticonModel = emoticonModel
            
            //计算行高
            let lineHight = UIFont.systemFont(ofSize: 16).lineHeight
            //设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHight, height: lineHight)
            //设置image
            att.image = image
            //创建一个可变的富文本
            let attr = NSAttributedString(attachment: att)
            
            //添加到富文本中
//            allAttr.append(allAttr)
            //获取光标位置
            let selectRange = textView.selectedRange
            //把点击的表情添加到textView中
//            allAttr.insert(attr, at: selectRange.location)
            //替换
            allAttr.replaceCharacters(in: selectRange, with: attr)
            //设置font
            allAttr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: allAttr.length))
            textView.attributedText = allAttr
            //让光标位置加一
            textView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            //开发者发送系统通知(使用系统通知名)
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            //textView 自己调用其身上的代理执行协议方法
            textView.delegate?.textViewDidChange!(textView)
        }
        
        //把对应的表情模型进行保存
        JBWEmoticonTools.share.saveRecentEmoticon(emoticonModel: emoticonModel)
        //刷新
        keyboardView.reloadRecentEmoticons()
    }
    
    //监听删除按钮点击通知
    @objc fileprivate func deleteBUttonClickNoti(){
        //删除textView 的文字或图片
        textView.deleteBackward()
    }
}
